<template>
  <q-card-section>
    <p class="text-grey-6">所有广告广告图片列表，可通过分类进行检索。</p>
    <q-table
      grid
      :data="table.tableContentData"
      :columns="table.columns"
      :visibleColumns="table.visibleColumns"
      row-key="index"
      :loading="table.loading"
      :pagination.sync="table.initialPagination"
      @request="requestPagination"
      rows-per-page-label="每页显示"
      flat
      bordered
      :dense="$q.screen.lt.md"
      :separator="table.separator"
      :selected-rows-label="selectedRowMessage"
      selection="multiple"
      :selected.sync="table.selected"
    >
      <template v-slot:top>
        <div class="col-md-2">
          <q-select
            outlined
            dense
            v-model="form.model"
            :options="form.options"
            label="按分类检索"
            clear-icon="mdi-close"
            clearable
            options-selected-class="text-primary"
            @input="getList(form.model, table.defaultPageIndex)"
          />
        </div>
        <q-space />
        <div class="col">
          <q-btn-group
            flat
            class="float-right"
          >
            <q-btn
              color="negative"
              text-color="white"
              icon="mdi-delete"
              label="批量删除"
              size="md"
              @click="getSelectedRows"
            />
            <q-btn
              color="primary"
              icon="mdi-table-row-plus-after"
              label="添加"
              size="md"
              @click="gotoAddItem"
            />
          </q-btn-group>
        </div>
      </template>
      <template v-slot:item="props">
        <div
          class="q-pa-xs col-xs-12 col-sm-6 col-md-4 col-lg-3  col-xl-2"
          :style="props.selected ? 'transform: scale(0.95);' : ''"
        >
          <q-card
            flat
            bordered
            :class="props.selected ? 'bg-grey-2' : ''"
          >
            <q-card-section>
              <q-checkbox
                dense
                v-model="props.selected"
                :label="props.row.AdName"
              />
            </q-card-section>
            <q-separator />
            <q-img :src="$utils.defaultImgSrc + props.row.Ad">
              <!-- <q-img src="https://cdn.quasar.dev/img/mountains.jpg"> -->
            </q-img>
            <q-card-section>
              <div class="text-caption text-grey-5">所属分类：{{ props.row.CategoryName }}</div>
            </q-card-section>
            <q-card-actions class="row">
              <q-btn
                class="col"
                icon="mdi-delete"
                label="删除"
                color="negative"
                flat
                @click="getDeleteRow(props.row)"
              />
              <q-btn
                class="col"
                icon="mdi-table-edit"
                label="编辑"
                flat
                color="primary"
                @click="gotoEditRow(props.row)"
              />
            </q-card-actions>
          </q-card>
        </div>
      </template>
      <template v-slot:pagination>
        <q-pagination
          v-model="table.initialPagination.current"
          :max="table.initialPagination.page"
          :boundary-links="true"
          @click="getList(form.model, table.initialPagination.current)"
        >
        </q-pagination>
      </template>
      <template v-slot:loading>
        <q-inner-loading
          showing
          color="primary"
        />
      </template>
    </q-table>
    <!-- 对话框-删除确认 -->
    <q-dialog v-model="dialog.delConfirm">
      <q-card>
        <q-card-section class="row items-center">
          <q-avatar
            icon="mdi-alert-circle-outline"
            text-color="negative"
          />
          <span class="q-ml-sm text-negative">确定要删除所选记录吗？</span>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn
            flat
            label="取消"
            v-close-popup
          />
          <q-btn
            flat
            label="确定删除"
            color="negative"
            v-close-popup
            @click="deleteRows(deleteID)"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-card-section>
</template>

<script>
import { mapMutations } from 'vuex'

// 定义获取二级分类的参数
const _mCode = {
  mCode: 'GG'
}

export default {
  name: 'PageAds',
  components: {
  },
  props: {},
  data () {
    return {
      // ---------- 下拉框
      form: {
        model: null,
        options: [],
        columnName: '',
      },
      // ---------- 表格
      table: {
        // 默认$Api参数
        defaultCategory: -1,
        defaultPageIndex: 1,
        // 初始化分页
        initialPagination: {
          sortBy: 'desc',
          descending: false,
          page: 1,
          rowsPerPage: this.$store.state.default.rowsPerPage,
          current: 1,
          rowsNumber: 0 //if getting data from a server
        },
        // 分割线模式可选值：horizontal (default)', 'vertical', 'cell', 'none'
        separator: 'horizontal',
        loading: true,
        // 可见列
        visibleColumns: [ 'Ad', 'CategoryName', 'AdName', 'AdNote', 'Status', 'Action'],
        columns: [
          {
            name: 'index',
            required: true,
            label: '序号',
            align: 'center',
            field: 'index'
          },
          { name: 'ID', align: 'center', label: 'ID', field: 'ID', style: 'max-width:50px'},
          // { name: 'UpCategory', align: 'left', label: '一级分类', field: 'UpCategory' },
          // { name: 'UpCategoryID', align: 'left', label: '一级分类ID', field: 'UpCategoryID' },
          { name: 'CategoryName', align: 'center', label: '二级分类', field: 'CategoryName' },
          { name: 'Ad', align: 'center', label: '广告图片缩略图', field: 'Ad' },
          { name: 'AdName', align: 'left', label: '广告图片名称', field: 'ProductName' },
          { name: 'AdNote', align: 'left', label: '广告图片链接', field: 'AdNote' },
          { name: 'PublicDate', align: 'center', label: '发布日期', field: 'PublicDate' },
          { name: 'Author', align: 'center', label: '发布者', field: 'Author' },
          { name: 'Status', align: 'center', label: '审核', field: 'Status' },
          { name: 'Action', align: 'center', label: '操作', field: '', style: 'min-width:220px' },
        ],
        tableContentData: [],
        selected: [],
      },
      // ---------- 对话框
      dialog: {
        delConfirm: false,
      },
      deleteID: []
    }
  },
  methods: {
    // 获取列表
    getList(modelValue, currentPage) {
      const _params = {
        pageIndex:currentPage,
        pageSize:this.table.initialPagination.rowsPerPage,
        ColumnID:this.table.defaultCategory
      }
      if (modelValue !== null) {
        _params.ColumnID = modelValue.value
      }
      this.$api.AdsParams('', 'get', _params).then (result => {
        // console.log(result)
        this.table.tableContentData = result.data
        this.table.initialPagination.rowsNumber = result.count
        this.table.initialPagination.page = Math.ceil(this.table.initialPagination.rowsNumber / this.table.initialPagination.rowsPerPage)
        // 生成序号 & 格式化日期，去掉时间
        this.table.tableContentData.forEach((row, index) => {
          row.index = index + 1
          row.PublicDate = this.$utils.initDate(row.PublicDate, 0, 10)
        })
        // 关闭加载动画
        this.table.loading = false
        // console.log(this.$utils.defaultImgSrc + result.data[0].Ad)
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
    },
    // 动态分页(下拉选择每页显示条数)
    requestPagination(props) {
      this.table.initialPagination.rowsPerPage = this.$utils.dynamicPagination(props)
      this.getList(this.form.model, this.table.defaultPageIndex)
    },
    // 获取分类过滤数据
    getCategory() {
      this.$api.MColumnOptionParams('GetMColumnList', 'get', _mCode).then (result => {
        // console.log(result)
        this.form.options = result
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })

    },
    // 显示多条选择行数量信息
    selectedRowMessage() {
      return this.table.selected.length === 0 ? '' : `选择了全部${this.table.tableContentData.length}条记录中的${this.table.selected.length} 条`
    },
    // 获取多条选择行ID值数组
    getSelectedRows() {
      this.deleteID = []
      if (this.table.selected.length > 0) {
        this.table.selected.map((row) => {
          this.deleteID.push( row.ID)
        })
        this.dialog.delConfirm = true
      } else {
        this.$utils.notify('请选择要删除的记录','red-8')
      }
    },
    // 获取单条删除的row信息
    getDeleteRow(row) {
      this.deleteID = []
      this.deleteID.push(row.ID)
      this.dialog.delConfirm = true
    },
    // 提交服务器并删除本地预存信息
    deleteRows(rowid) {
      // 删除
      const _ids = rowid
      this.$api.AdsData('', 'delete', _ids).then (result => {
        // console.log(result)
         if ( result === 'success') {
          //  重新请求数据列表
           this.getList(this.form.model, this.table.defaultPageIndex)
         } else if ( result === 'error' ) {
           this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
         }
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
      this.deleteID = []
      this.table.selected = []
    },
    // btn-编辑
    gotoEditRow(value) {
      this.$router.push('/Ads/EditAd/' + value.ID);
    },
    // btn-添加
    gotoAddItem() {
      this.$router.push('/Ads/AddAd');
    },
    // session过期操作
    ...mapMutations(['changeLogin']),
    unauthorized() {
      // 弹出警告框
      this.$utils.notify('身份信息过期','red-8')
      // 清除vuex中的token
      this.changeLogin({ Authorization: '' })
      // 路由跳转
      this.$router.push('/Login', onComplete => {}, onAbort => {});
    }
  },
  computed: {
    // cardContainerClass() {
    //   if (this.$q.screen.gt.xs) {
    //     return 'grid-masonry grid-masonry--' + (this.$q.screen.gt.sm ? '3' : '2')
    //   }
    //   return void 0
    // },
  },
  mounted() {
    this.getList(this.form.model, this.table.defaultPageIndex)
    this.getCategory()
  },
}
</script>
<style scoped>
</style>